/*
 * @Description: 描述信息
 * @Version: 版本号
 * @Author: xuebao
 * @Date: 2023-12-05 14:14:29
 * @LastEditors: renmengxue
 * @LastEditTime: 2023-12-08 15:25:20
 */
import { createRouter, createWebHistory } from 'vue-router'
import store from './store'
import axios from 'axios'
import { useUserStore } from './store/user'
const routerHistory = createWebHistory()
const router = createRouter({
  history: routerHistory,
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('./views/Home.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('./views/Login.vue'),
      meta: {
        redirectAlreadyLogin: true
      }
    },
    {
      path: '/column/:id',
      name: 'column',
      component: () => import('./views/ColumnDetail.vue')
    },
    {
      path: '/posts/:id',
      name: 'posts',
      component: () => import('./views/PostDetail.vue')
    },
    {
      path: '/crate',
      name: 'crate',
      component: () => import('./views/CreatePosts.vue'),
      meta: {
        requiredLogin: true// 必须登陆之后才允许访问这个页面
      }
    },
    {
      path: '/signup',
      name: 'signup',
      component: () => import('./views/Signup.vue')
    }
  ]
})
// router.beforeEach((to, from, next) => {
//   if (to.meta.requiredLogin && !store.state.user.isLogin) {
//     next({ name: 'login' })
//   } else if (to.meta.redirectAlreadyLogin && store.state.user.isLogin) {
//     next('/')
//   } else {
//     next()
//   }
// })

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const { token } = userStore
  // const { user, token } = store.state
  const { requiredLogin, redirectAlreadyLogin } = to.meta

  if (!userStore.isLogin) {
    // 没有登陆的
    if (userStore.token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
      userStore.fetchCurrentUser().then(() => {
        // 异步请求发送
        if (redirectAlreadyLogin) {
          next('/')
        } else {
          next()
        }
      }).catch((e) => {
        // 既然失败了就说明这个token 不能用了 需要清楚掉
        userStore.logout()
        // 失败了跳转到登陆
        next('/login')
      })
      // 有token
    } else {
      // 没有token
      if (requiredLogin) {
        // 如果需要登陆才能访问
        next('login')
      } else {
        next()
      }
    }
  } else {
    // 已经登陆的

    if (redirectAlreadyLogin) {
      next('/')
    } else {
      next()
    }
  }
})

export default router
